<!--
  * 工单生产计划
  *
  * @Author:    lmabbe
  * @Date:      2025-06-26 19:38:05
  * @Copyright  lmabbe
-->
<template>
  <!---------- 查询表单form begin ----------->
  <div class="smart-query-form">
    <a-form size="small" style="margin-bottom: 10px">
      <a-row class="smart-query-form-row">
        <a-form-item class="smart-query-form-item" label="制程类别">
          <DictSelect size="small" v-model:value="queryForm.processCategory" dict-code="PROCESS_CATEGORY" placeholder="制程类别" width="200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="生产产线">
          <a-select
            v-model:value="queryForm.lineId"
            :allowClear="true"
            :style="`width: 200px`"
            placeholder="请选择生产产线"
            @change="
              (value) => {
                form.lineName = productLineData.find((item) => item.lineId === value).lineName;
              }
            "
          >
            <a-select-option v-for="item in productLineData" :key="item.lineId" :value="item.lineId">
              {{ item.lineName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="工单ID">
          <a-input v-model:value="queryForm.workOrderId" placeholder="工单ID" style="width: 200px" />
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="计划状态:">
          <SmartEnumSelect width="200px" size="small" v-model:value="queryForm.planStatus" enum-name="WORK_ORDER_PRODUCTION_PLAN_PLAN_STATUS_ENUM" />
        </a-form-item>
        <a-form-item class="smart-query-form-item" label="创建时间">
          <a-range-picker v-model:value="queryForm.createTime" :presets="defaultTimeRanges" style="width: 200px" @change="onChangeCreateTime" />
        </a-form-item>
        <a-form-item class="smart-query-form-item">
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button class="smart-margin-left10" @click="resetQuery">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button v-privilege="'productionPlan:add'" size="small" type="primary" @click="showForm">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
        <a-button v-privilege="'productionPlan:audit'" :disabled="selectPlan?.postedFlag" size="small" type="primary" @click="confirmAudit"
          >审核站位表
        </a-button>
        <a-button size="small" type="primary" @click="setPositionParse">站位表解析模板</a-button>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
      v-privilege="'productionPlan:query'"
      :columns="columns"
      :dataSource="tableData"
      :loading="tableLoading"
      :pagination="false"
      :custom-row="
        (res) => {
          return {
            onclick: () => {
              onSelectChange(res.planId);
            },
          };
        }
      "
      :row-selection="{ type: 'radio', selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      :scroll="{ y: 200 }"
      bordered
      rowKey="planId"
      size="small"
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'planStatus'">
          <span>{{ $smartEnumPlugin.getDescByValue('WORK_ORDER_PRODUCTION_PLAN_PLAN_STATUS_ENUM', text) }}</span>
        </template>
        <template v-if="column.dataIndex === 'planProductionLayout'">
          <DictLabel :data-value="text" :dict-code="'PRODUCT_BRAND'" />
        </template>

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button
              v-if="record.postedFlag && record.planStatus === 10"
              v-privilege="'productionPlan:activate'"
              type="link"
              @click="activate(record)"
              >激活
            </a-button>
            <a-button v-if="record.planStatus === 30" v-privilege="'productionPlan:pauseProduce'" type="link" @click="pauseProduce(record)"
              >暂停生产
            </a-button>
            <a-button v-if="record.planStatus === 40" v-privilege="'productionPlan:reactivate'" type="link" @click="reactivate(record)"
              >重新生产
            </a-button>
            <a-button
              v-privilege="'productionPlan:forcedShutdown'"
              v-if="record.planStatus !== 10 && record.planStatus !== 50 && record.planStatus !== 60"
              type="link"
              @click="openForcedShutdown(record)"
            >
              强制关停
            </a-button>
            <a-button v-if="record.planStatus === 10" v-privilege="'productionPlan:update'" type="link" @click="showForm(record)">编辑 </a-button>
            <a-button v-if="record.planStatus === 10" v-privilege="'productionPlan:delete'" danger type="link" @click="onDelete(record)"
              >删除
            </a-button>
          </div>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :defaultPageSize="queryForm.pageSize"
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :show-total="(total) => `共${total}条`"
        :total="total"
        show-less-items
        showQuickJumper
        showSizeChanger
        @change="queryData"
        @showSizeChange="queryData"
      />
    </div>
  </div>
  <PlanTabs ref="planRef" />
  <ProductionPlanForm ref="formRef" @reloadList="queryData" />
  <ForcedShutdown ref="forcedShutdownRef" @reloadList="queryData" />
  <PositionTemplateParseSetting ref="positionParseSettingRef" />
</template>
<script setup>
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';

  import { productionPlanApi } from '/@/api/business/product/order/production-plan-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import ProductionPlanForm from './production-plan-form.vue';
  import ForcedShutdown from './components/forced-shutdown.vue';
  import DictLabel from '/@/components/support/dict-label/index.vue';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import DictSelect from '/@/components/support/dict-select/index.vue';
  import { productLineInfoApi } from '/@/api/business/product/line/product-line-info-api.js';
  import PlanTabs from './planTabs.vue';
  import { defaultTimeRanges } from '/@/lib/default-time-ranges.js';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
  import PositionTemplateParseSetting from '/@/views/business/product/plan/components/positionTemplateParseSetting.vue';
  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '生产计划ID',
      dataIndex: 'planId',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '工单编号',
      dataIndex: 'workOrderCode',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '制程类别',
      dataIndex: 'processCategory',
      ellipsis: true,
      width: '60px',
      align: 'center',
    },
    {
      title: '产线名称',
      dataIndex: 'lineName',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '站位表版本',
      dataIndex: 'positionVer',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '计划状态',
      dataIndex: 'planStatus',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '计划生产数量',
      dataIndex: 'planProductionQty',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '已生产数量',
      dataIndex: 'completedQty',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '计划生产版面',
      dataIndex: 'planProductionLayout',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '标准产能',
      dataIndex: 'standardCapacity',
      ellipsis: true,
      width: '100px',
      align: 'center',
    },
    {
      title: '计划开始时间',
      dataIndex: 'planStartTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '计划结束时间',
      dataIndex: 'planEndTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '实际开始时间',
      dataIndex: 'actualStartTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '实际结束时间',
      dataIndex: 'actualEndTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },

    {
      title: '暂停时长',
      dataIndex: 'pauseDuration',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '强制关闭原因',
      dataIndex: 'forcedShutdownReason',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: '200px',
      align: 'center',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      ellipsis: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      ellipsis: true,
      width: '150px',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 200,
      align: 'center',
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    createTime: [], //创建时间
    createTimeBegin: undefined, //创建时间 开始
    createTimeEnd: undefined, //创建时间 结束
    processCategory: undefined, //制程类别
    lineId: undefined, //产线ID
    workOrderId: undefined, //工单ID
    planStatus: undefined, //计划状态: [1.等待激活 2.上料中 3.生产中 4.暂停生产 5.生产完成 6.强制关闭]
    pageNum: 1,
    pageSize: 10,
  };
  // 查询表单form
  const queryForm = reactive({ ...queryFormState });
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await productionPlanApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      onSelectChange(tableData.value[0].planId);
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  function onChangeCreateTime(dates, dateStrings) {
    queryForm.createTimeBegin = dateStrings[0];
    queryForm.createTimeEnd = dateStrings[1];
  }

  onMounted(() => {
    queryData();
    loadProductLine();
  });

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref();

  function showForm(data) {
    formRef.value.show(data);
  }

  // ---------------------------- 单个删除 ----------------------------
  //确认删除
  function onDelete(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        requestDelete(data);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  //请求删除
  async function requestDelete(data) {
    SmartLoading.show();
    try {
      let deleteForm = {
        goodsIdList: selectedRowKeyList.value,
      };
      await productionPlanApi.delete(data.planId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);
  const planRef = ref();
  const selectPlan = ref();

  function onSelectChange(selectedRowKeys, v) {
    if (selectedRowKeys instanceof Array) {
      selectedRowKeys = selectedRowKeys[0];
    }
    selectedRowKeyList.value = [selectedRowKeys];
    let plan = tableData.value.filter((item) => item.planId === selectedRowKeys);
    selectPlan.value = plan[0];
    planRef.value.setPlanInfo(plan[0]);
  }

  // 批量删除
  function confirmAudit() {
    Modal.confirm({
      title: '提示',
      content: '确定要审核站位表数据吗?审核之后站位表数据将不能修改！',
      okText: '审核',
      okType: 'danger',
      onOk() {
        requestAudit();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  const productLineData = ref();

  function loadProductLine() {
    productLineInfoApi.all().then((res) => {
      productLineData.value = res.data;
    });
  }

  //请求批量删除
  async function requestAudit() {
    try {
      SmartLoading.show();
      await productionPlanApi.audit(selectedRowKeyList.value, !selectPlan.value.postedFlag);
      message.success('审核成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  function activate(record) {
    productionPlanApi.activate(record.planId).then((res) => {
      message.success('操作成功');
      onSearch();
    });
  }

  function pauseProduce(record) {
    productionPlanApi.pauseProduce(record.planId).then((res) => {
      message.success('操作成功');
      onSearch();
    });
  }

  function reactivate(record) {
    productionPlanApi.reactivate(record.planId).then((res) => {
      message.success('操作成功');
      onSearch();
    });
  }

  const forcedShutdownRef = ref();

  function openForcedShutdown(record) {
    forcedShutdownRef.value.show(record);
  }

  const positionParseSettingRef = ref();

  function setPositionParse() {
    positionParseSettingRef.value.showModal();
  }
</script>
